<template>
    <div class="search-container">
        <!-- 顶部搜索栏 -->
        <!-- Tips: 在 van-search 外层增加 form 标签，且 action 不为空，即可在 iOS 输入法中显示搜索按钮。 -->
        <form action="/" class="search-form">
            <van-search v-model="searchText" show-action placeholder="请输入搜索关键词" background="#3296fa" @focus="isResultShow = false" @search="onSearch" @cancel="onCancel" />
        </form>
        <!-- 搜索结果 -->
        <search-result :searchText="searchText" v-if="isResultShow"></search-result>
        <!-- 搜索建议 -->
        <search-suggestion @search="onSearch" :searchText="searchText" v-else-if="searchText"></search-suggestion>
        <!-- 搜索历史 -->
        <search-history :searchHistory="searchHistory" @update-search-history="searchHistory = []" @search="onSearch" v-else></search-history>
    </div>
</template>

<script>
import SearchHistory from "./components/search-history.vue";
import SearchResult from "./components/search-result.vue";
import SearchSuggestion from "./components/search-suggestion.vue";
export default {
  components: {
    SearchHistory,
    SearchResult,
    SearchSuggestion,
  },
  data() {
    return {
      searchText: "",
      isResultShow: false,
      searchHistory: localStorage.getItem("searchHistoryTS") || [],
    };
  },
  methods: {
    onSearch(val) {
      this.isResultShow = true;
      const index = this.searchHistory.indexOf(val);
      if (index !== -1) {
        this.searchHistory.splice(index, 1);
      }
      this.searchHistory.unshift(val);
      this.searchText = val;
    },
    onCancel() {
      this.$router.back();
    },
  },
  watch: {
    searchHistory(val) {
      localStorage.setItem("searchHistoryTS", val);
    },
  },
};
</script>

<style lang="scss" scoped>
.search-container {
  padding-top: 108px;
  .van-search__action {
    color: #fff;
  }
  .search-form {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1;
  }
}
</style>
